<!-- <template>
  <div class="grade-distribution-bar-chart">
    <div ref="chartContainer" class="chart-container" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts/lib/echarts.js';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/title';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/tooltip';
import { getGradeDistribution } from '@/api/grade/grade'; // 确保引入路径正确
  export default {
  data() {
    return {
      chart: null,
      loading: true,
      gradeRanges: [
        { name: '<60', key: '小于60' },
        { name: '60-69', key: '60-69' },
        { name: '70-79', key: '70-79' },
        { name: '80-89', key: '80-89' },
        { name: '≥90', key: '90-100' }
      ]
    }
  },
  mounted() {
    this.initChart();
    this.loadData();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
    methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.chart.setOption({
        xAxis: { type: 'category', data: this.gradeRanges.map(r => r.name) },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: [] }]
      });
    },
    
    async loadData() {
      try {
        const rawData = await getGradeDistribution();
        if (!rawData) throw new Error('空数据');
        
        const seriesData = this.gradeRanges.map(range => {
          const value = rawData[range.key];
          return typeof value === 'number' ? value : 0;
        });
        
        this.chart.setOption({
          series: [{ data: seriesData }],
          yAxis: { max: Math.max(...seriesData) * 1.1 }
        });
      } catch (error) {
        console.error('加载失败:', error);
        this.useMockData();
      } finally {
        this.loading = false;
      }
    },

    // 处理分布数据
    processDistributionData(data) {
      console.log('后端返回数据:', data); // 添加日志打印后端返回数据
      if (!data || Object.keys(data).length === 0) {
        console.warn('成绩分布数据为空');
        this.useMockData();
        return;
      }
      const gradeCounts = this.gradeRanges.map(range => data[range.name]);
      console.log('更新图表数据，数据为', gradeCounts);
      this.chart.setOption({
        series: [{
          data: gradeCounts
        }]
      });
      this.distributionData = data;
    },


    useMockData() {

      const mockData = [
        { name: '小于60', count: 3 },
        { name: '60-69', count: 7 },
        { name: '70-79', count: 12 },
        { name: '80-89', count: 10 },
        { name: '90-100', count: 5 }
      ];
      const gradeCounts = mockData.map(item => item.count);
      this.chart.setOption({
        series: [{
          data: gradeCounts
        }]
      });
      this.distributionData = mockData;
    },

    showErrorToast() {
      this.$message({
        message: '获取成绩分布数据失败，请稍后再试',
        type: 'error',
        duration: 3000
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.grade-distribution-bar-chart {
  width: 100%;
  height: 100%;

 .chart-container {
    width: 100%;
    height: 100%;
  }
}
</style> -->

<template>
  <div class="grade-distribution-bar-chart">
    <div v-loading="loading" element-loading-text="数据加载中...">
      <div ref="chartContainer" class="chart-container"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/grid'
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'
import { getGradeDistribution } from '@/api/grade/grade'

export default {
  name: 'GradeDistributionBarChart',
  props: {
    courseId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      loading: true,
      gradeRanges: [
        { name: '<60', key: '小于60' },
        { name: '60-69', key: '60-69' },
        { name: '70-79', key: '70-79' },
        { name: '80-89', key: '80-89' },
        { name: '≥90', key: '90-100' }
      ]
    }
  },
  mounted() {
    this.initChart()
    this.loadData()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer)
      this.chart.setOption({
        title: {
          text: '成绩分布统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>人数: {c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.gradeRanges.map(r => r.name),
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '人数'
        },
        series: [{
          name: '人数',
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: function(params) {
              const colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae']
              return colorList[params.dataIndex]
            }
          },
          label: {
            show: true,
            position: 'top'
          },
          data: []
        }]
      })
    },

    async loadData() {
      try {
        const response = await getGradeDistribution()
        const rawData = response.data || response
        
        console.log('API返回数据:', rawData) // 调试用
        
        if (!rawData || typeof rawData !== 'object') {
          throw new Error('无效的数据格式')
        }
        
        const seriesData = this.gradeRanges.map(range => {
          // 处理可能的键名差异
          const value = rawData[range.key] || rawData[range.name] || 0
          return Number(value) || 0
        })

        this.chart.setOption({
          series: [{
            data: seriesData
          }],
          yAxis: {
            max: Math.max(...seriesData) * 1.2 || 10 // 默认最大值
          }
        })
      } catch (error) {
        console.error('加载成绩分布失败:', error)
        this.useMockData()
        this.showErrorToast('获取成绩分布失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    useMockData() {
      // 保留模拟数据作为fallback
      const mockData = [5, 10, 15, 20, 10]
      this.chart.setOption({
        series: [{
          data: mockData
        }]
      })
    },

    showErrorToast(message) {
      this.$message({
        message: message || '获取成绩分布数据失败，已显示模拟数据',
        type: 'error',
        duration: 3000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.grade-distribution-bar-chart {
  width: 100%;
  height: 100%;
  min-height: 400px;

  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 400px;
  }
}
</style>